package domain

import (
	"github.com/lab-online/internal/shared/code"
	"github.com/lab-online/internal/user/constant"
	"github.com/lab-online/internal/user/entity"
	"github.com/lab-online/internal/user/valueobject"
	"github.com/lab-online/pkg/auth"
)

func (d *Domain) UpdatePassword(authEntity auth.AuthEntity, patch *valueobject.PasswordPatch) error {
	savedUser, dbErr := d.repository.GetUserByUsername(patch.Username)
	if dbErr != nil {
		return code.ErrorPicker(dbErr, code.DatabaseUserNotFound, constant.RESTErrUserNotFound)
	}

	if !savedUser.CanHandleUser(authEntity, false) {
		return constant.RESTErrNoPermissionPatch
	}

	if authEntity.IsSelf(savedUser.GetUsername()) && !savedUser.ComparePassword(patch.OldPassword) {
		return constant.RESTErrPasswordNotMatch
	}

	savedUser.Update(entity.WithPassword(patch.NewPassword))
	if err := savedUser.HashPassword(); err != nil {
		return constant.RESTErrPasswordHashError
	}

	_, dbErr = d.repository.SaveUser(savedUser)
	return dbErr
}
